package org.rency.spring.cloud.boot.mvc.controller;

import org.rency.spring.cloud.boot.mvc.common.BaseAction;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * ${todo}
 *
 * @author: Created by user_rcy@163.com on 2016/8/19.
 * @version: V1.0.0
 * @since JDK 1.8
 */
@Controller
@RequestMapping("/")
public class IndexController extends BaseAction {

    @RequestMapping("loginSuccess")
    public ModelAndView redirect(){
        return super.redirect(null);
    }

    @RequestMapping
    public ModelAndView main(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return this.view("normal","index");
    }

    @RequestMapping(value="login",method = RequestMethod.GET)
    public ModelAndView loginInput(@RequestHeader HttpHeaders headers,HttpServletRequest request, CsrfToken token){
        String fromUrl = this.getFromAddr(headers,request);
        logger.debug("请求登录, 请求来源:{}.",fromUrl);
        respData.put("tokenName",token.getParameterName());
        respData.put("tokenValue",token.getToken());
        AuthenticationException authenticationException = (AuthenticationException) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");
        String message = null;
        if(authenticationException != null){
            message = this.getAuthenticationMessage(authenticationException);
            logger.info("登录失败:{}-{}.",message,authenticationException.getMessage());
            this.failed(message);
        }
        return this.view("normal","login");
    }

    @RequestMapping(value="logout")
    public ModelAndView logout(HttpServletRequest request){
        request.getSession().invalidate();
        return this.view("normal","login");
    }
}